package com.shibo.generator.service;

import com.shibo.generator.entity.TableColumns;
import com.shibo.generator.request.TableRequest;
import com.shibo.generator.temUtils.TemCommon;
import com.shibo.generator.util.Constant;
import com.shibo.generator.util.IoUtils;
import com.shibo.generator.util.ReplaceUtlis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/*
* 数据库表生成器
* */
@Service
public class TableGenerator {

    @Autowired private TableInfoService tableInfoService;

    @Autowired private TemCommon temCommon;
    /*
    * 创建表
    * */
    public void createTable(TableRequest tableRequest) {
        if (tableRequest.getList().size() > 0) {
            //删除已存在的表
            tableInfoService.execSql("DROP TABLE IF EXISTS "+ tableRequest.getName());
            //1.读取创建表模板
            String tem = new IoUtils().read(temCommon.returnFileName("createTable"));
            //2.准备模板数据
            Map<String,Object> map = new HashMap<>();
            StringBuilder primaryIds = new StringBuilder("");
            map.put("increment",tableRequest.isAutoIncrement() ? "AUTO_INCREMENT = 1" : "");
            map.put("table",tableRequest.getName());
            StringBuilder sb = new StringBuilder();
            String format = "`%s` %s(%s) %s COMMENT '%s' %s";
            for (TableColumns tableColumns : tableRequest.getList()) {
                boolean AutoIncrement = tableRequest.isAutoIncrement() && tableColumns.getName().equals(tableRequest.getAutoIncrementField());
                sb.append(String.format(format,tableColumns.getName(),tableColumns.getType(),tableColumns.getLen(),
                        tableColumns.isNotNull() ? "NOT NULL" : "",tableColumns.getDesc(),AutoIncrement ? "AUTO_INCREMENT" : ""));
                sb.append(",\n");
                if (tableColumns.isPrimary())
                    primaryIds.append("`").append(tableColumns.getName()).append("`").append(",");
            }
            map.put("tableData",sb.substring(0,sb.lastIndexOf(",")));
            map.put("primary","".equals(primaryIds.toString()) ? "" : ",  PRIMARY KEY ("+primaryIds.substring(0,primaryIds.lastIndexOf(","))+")");
            //3.执行sql
            tableInfoService.execSql(ReplaceUtlis.replace(tem, map));
        }
    }
}
